package com.zidian.study.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.zidian.study.activity.TaskActionDetailActivity;
import com.zidian.study.adapter.QuestionAdapter;
import com.zidian.study.bean.TaskActionBean;
import com.zidian.study.globa.BaseFragment;
import com.zidian.study.globa.Constant;
import com.zidian.study.utils.ToastUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import com.zidian.student.trucks.R;

/**
 * Created by Administrator on 2016/8/26 0026.
 */
public class QuestionFragment extends BaseFragment {


    public SwipeRefreshLayout mSwipeRefreshWidget;
    private RecyclerView mRecyclerView;


    boolean isLoading;
    private QuestionAdapter adapter;
    private Handler handler = new Handler();
//    private List<Map<String, Object>> data = new ArrayList<>();


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_work;
    }


    public static QuestionFragment newInstance() {

        return new QuestionFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {


//        adapter = new QuestionAdapter(getActivity(), data);
        mSwipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.list);

        initView();
        initData();


    }

    public void initView() {

        mSwipeRefreshWidget.setColorSchemeResources(R.color.green);

        mSwipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshWidget.setRefreshing(true);
            }
        });
        mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                try {
//                    dataBeanList.clear();
//                    run("0");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
            }
        });


        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);
//        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = mSwipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
//                        try {
//                            run(dataBeanList.size() + "");
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }

                    }
                }
            }
        });


        //添加点击事件
        adapter.setOnItemClickListener(new QuestionAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                startActivity(TaskActionDetailActivity.class);
            }

            @Override
            public void onItemLongClick(View view, int position) {


            }
        });

    }

    public void initData() {
//        try {
//            run("0");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }

    /**
     * 获取测试数据
     */
    private void getData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getData();
            }
        }, 1500);
        adapter.notifyDataSetChanged();
        mSwipeRefreshWidget.setRefreshing(false);
        adapter.notifyItemRemoved(adapter.getItemCount());
    }

//    private List<TaskActionBean.DataBean> dataBeanList = new ArrayList<TaskActionBean.DataBean>();

    public void run(String startrow) throws IOException {
        String url = Constant.URL_GOAL + "activity/select";

        Map<String, String> map = new HashMap<>();
        map.put("startrow", startrow);
        map.put("pageSize", "10");
        map.put("activityTitle", "");


        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {

                Log.e("T", response);

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {

                        if (resultCode == 201) {
                            isLoading = true;
                            adapter.setMore(false);
                            mSwipeRefreshWidget.setRefreshing(false);
                            return;
                        }

                        ToastUtil.showToast(mActivity.getApplication(), "获取活动失败！");
                        return;
                    }

                } catch (JSONException e) {


                }
                mSwipeRefreshWidget.setRefreshing(false);
                Gson gson = new Gson();
                TaskActionBean actionBean = gson.fromJson(response, TaskActionBean.class);

                if (actionBean.isSuccess()) {

                    if (actionBean.getData().size() < 10) {
                        isLoading = true;
                        adapter.setMore(false);
                    } else {
                        isLoading = false;
                        adapter.setMore(true);
                    }
//                    dataBeanList.addAll(actionBean.getData());
                    getData();
                }

            }
        });

    }

}
